package com.newlink.building.common_base.utils

import android.annotation.SuppressLint
import android.content.Context
import android.os.PowerManager
import android.os.Vibrator
import android.util.Log
import androidx.collection.arraySetOf

class Base_VibratorHelper private constructor() {

    private var mVibrator: Vibrator? = null
    private var mWakeLock: PowerManager.WakeLock? = null

    // 未避免重复用Set记录震动Event队列
    private val alarmSet: MutableSet<Long> = arraySetOf()

    // 是否处于震动状态
    private var isVibrating = false

    companion object {
        private val sInstance = Base_VibratorHelper()

        @SuppressLint("InvalidWakeLockTag")
        fun getInstance(context: Context): Base_VibratorHelper {
            if (sInstance.mVibrator == null) {
                sInstance.mVibrator = context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
                val powerManager = (context.getSystemService(Context.POWER_SERVICE) as PowerManager)
                sInstance.mWakeLock = powerManager.newWakeLock(
                    PowerManager.FULL_WAKE_LOCK or PowerManager.ACQUIRE_CAUSES_WAKEUP,
                    "VibrationWakeLock"
                )
            }
            return sInstance
        }
    }

    fun startVibration(
        pattern: LongArray = longArrayOf(0, 1000, 300),
        repeat: Int = 0,
        alarmId: Long = 0L
    ) {
        if (alarmId != 0L) {
            alarmSet.add(alarmId)
        }
        Log.e("FvlVibratorHelper", "startVibration: alarmId:$alarmId alarmSet:$alarmSet")
        if (!hasVibration()) {
            mWakeLock?.acquire()
            mVibrator?.vibrate(pattern, repeat)
            isVibrating = true
        }
    }

    fun stopVibration(alarmId: Long = 0) {
        if (alarmId != 0L) {
            alarmSet.remove(alarmId)
        }
        Log.e("FvlVibratorHelper", "stopVibration: alarmId:$alarmId alarmSet:$alarmSet")
        if (alarmSet.size == 0) {
            mVibrator?.cancel()
            isVibrating = false
            if (mWakeLock?.isHeld == true) {
                mWakeLock?.release()
            }
        }
    }

    fun hasVibration(): Boolean {
        return isVibrating
    }

    fun activeVibration() {
        if (isVibrating && alarmSet.size > 0) {
            isVibrating = false
            startVibration()
        }
    }

    fun clear() {
        Log.e("FvlVibratorHelper", "clear alarmSet")
        alarmSet.clear()
        mVibrator?.cancel()
        isVibrating = false
        if (mWakeLock?.isHeld == true) {
            mWakeLock?.release()
        }
    }
}